import random
from typing import List, Dict
from datetime import datetime
from .game_state import FactorDevelopment, GameWorld

class NarrativeEngine:
    """叙事引擎"""
    
    def __init__(self):
        self.story_templates = self._load_story_templates()
        self.dialogue_templates = self._load_dialogue_templates()
        self.historical_events = []
    
    def _load_story_templates(self) -> Dict:
        """加载故事模板"""
        return {
            "level_up": [
                "{name}在艰苦的训练中突破自我，达到了新的境界。",
                "{name}领悟了新的力量，等级提升到了{level}。",
                "经过不懈努力，{name}的实力得到了显著提升。"
            ],
            "event_participation": [
                "{name}勇敢地参与了{event_name}，展现了非凡的勇气。",
                "在{event_name}中，{name}发挥了关键作用。",
                "{name}与其他因子协同作战，共同面对{event_name}的挑战。"
            ],
            "travel": [
                "{name}踏上了前往{location}的旅程。",
                "{name}穿越险峻的地形，向着目标前进。",
                "在旅途中，{name}遇到了各种挑战和机遇。"
            ]
        }
    
    def _load_dialogue_templates(self) -> Dict:
        """加载对话模板"""
        return {
            "greeting": [
                "愿翁法罗斯之光指引你，{name}。",
                "新的轮回已经开始，{name}，你准备好了吗？",
                "铁幕正在逼近，{name}，我们必须加快行动。"
            ],
            "battle": [
                "为了翁法罗斯！{name}发起攻击！",
                "不会让你得逞的！{name}坚守阵地！",
                "这就是我们的力量！{name}释放技能！"
            ]
        }
    
    def generate_factor_story(self, factor: FactorDevelopment, event_type: str, **kwargs) -> str:
        """生成因子故事"""
        templates = self.story_templates.get(event_type, [])
        if templates:
            template = random.choice(templates)
            story = template.format(name=factor.name, **kwargs)
            
            # 记录历史事件
            self.historical_events.append({
                "timestamp": datetime.now(),
                "factor": factor.name,
                "event_type": event_type,
                "story": story
            })
            
            return story
        return f"{factor.name} 经历了 {event_type} 事件。"
    
    def generate_dialogue(self, speaker: str, dialogue_type: str, **kwargs) -> str:
        """生成对话"""
        templates = self.dialogue_templates.get(dialogue_type, [])
        if templates:
            template = random.choice(templates)
            return template.format(name=speaker, **kwargs)
        return f"{speaker} 说道：..."
    
    def generate_cycle_summary(self, game_world: GameWorld, cycle_results: Dict) -> str:
        """生成轮回总结"""
        summary = f"""
# 翁法罗斯纪事 - 第{game_world.current_cycle}轮回总结

## 轮回概况
- **持续时间**: {game_world.current_time} 时间单位
- **铁幕进度**: {game_world.iron_curtain_progress}%
- **存活因子**: {sum(1 for f in game_world.factors if f.is_alive)} / {len(game_world.factors)}
- **触发事件**: {len([e for e in game_world.events if e.completed])}

## 因子表现
"""
        
        for factor in game_world.factors:
            summary += f"""
### {factor.name} ({factor.factor_type.value})
- **最终等级**: {factor.level}
- **属性发展**: 攻击{factor.attributes['attack']:.1f} 防御{factor.attributes['defense']:.1f} 
               生命{factor.attributes['health']:.1f} 治疗{factor.attributes['healing']:.1f}
- **移动距离**: {len(factor.development_path)} 个地点
- **状态**: {'存活' if factor.is_alive else '阵亡'}
"""
        
        summary += f"""
## 关键事件回顾
"""
        
        important_events = [log for log in game_world.game_log[-10:]]  # 最后10个事件
        for event in important_events:
            summary += f"- 时间 {event['timestamp']}: {event['message']}\n"
        
        summary += f"""
## 轮回评价
{self._generate_evaluation(cycle_results)}
"""
        return summary
    
    def _generate_evaluation(self, cycle_results: Dict) -> str:
        """生成轮回评价"""
        performance = cycle_results.get('overall_performance', 0.5)
        
        if performance >= 0.8:
            return "本次轮回表现卓越！因子们展现了强大的协作能力和成长潜力。"
        elif performance >= 0.6:
            return "表现良好，但在某些方面还有提升空间。"
        elif performance >= 0.4:
            return "表现一般，需要更好的策略规划。"
        else:
            return "表现不佳，建议重新评估发展策略。"
    
    def generate_prophecy(self, iron_curtain_progress: int) -> str:
        """生成预言"""
        prophecies = [
            "当铁幕笼罩大地，十二星火将重燃希望。",
            "在轮回的尽头，新的传奇即将开始。", 
            "古老的预言正在逐步实现，命运之轮已然转动。",
            "黑暗中的微光，将是破晓的前兆。"
        ]
        
        if iron_curtain_progress > 50:
            prophecies.extend([
                "铁幕已过半，时间所剩无几。",
                "最终决战即将来临，准备好面对来古士的真正力量。"
            ])
        
        return random.choice(prophecies)